﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPop.Pop3;
using System.Threading;
using OpenPop.Mime;
using PInitiatives.Helpers;
using PInitiatives.Models;

namespace PInitiatives.Outlook
{
    public class EmailWorker : ObservableSubject
    {
        bool working;
        bool stopped;
        EmailAccessStrategy emailPopStrategy = new EmailPopInterface();

        public void DoWork()
        {
            System.Diagnostics.Debug.Write("Starting EmailPopWorker Thread\n");
            //sleep a bit at the begining
            Thread.Sleep(2000);
            working = true;
            stopped = false;
            List<AcceptanceMessage> acceptanceMessages;
            List<String> rawTextMessages;
            try{
                while (working) {
                    rawTextMessages = emailPopStrategy.EmailRetrievingAlgorithm();
                    printOutMessages(rawTextMessages);
                    acceptanceMessages = OutlookMeetingParser.getInstance().parseMessages(rawTextMessages);
                    processAcceptanceMessages(acceptanceMessages);                        
                    Thread.Sleep(2000);//sleep a bit every iteration
                }
            }
            catch (Exception ex)
            {
                stopped = true;
                System.Diagnostics.Debug.Write("EmailPopWorker.DoWork() exception: " + ex.Message + "\n");
                Notify();
            }
            stopped = true;
        }

        



// TEMPLATE METHODS
        private void printOutMessages(List<string> rawTextMessages)
        {
            int counter = 0;
            foreach (String s in rawTextMessages)
            {
                counter++;
                System.Diagnostics.Debug.Write("---WIADOMOŚĆ: " + counter + " ---\n");
                System.Diagnostics.Debug.Write(s + "\n\n\n");
            }
        }


        private void processAcceptanceMessages(List<AcceptanceMessage> acceptanceMessages)
        {
            foreach (AcceptanceMessage acceptanceMessage in acceptanceMessages)
            {
                PInitiativesEntities db = new PInitiativesEntities();
                Guid tmp = acceptanceMessage.getUID();
                AcceptanceList al = db.AcceptanceLists.SingleOrDefault(a => a.Code == tmp);
                System.Diagnostics.Debug.Write("Iniciatywa ID: " + acceptanceMessage.getUID() + " ");
                if (al != null)
                {
                    if (acceptanceMessage.isAccepted())
                    {
                        Initiative initative = al.GetInitative();
                        if (initative != null)
                        {
                            if (initative.HasFreeSpace)
                            {
                                //initative.addInitiativeUsers(al.User);
                                InitiativeUser iu = new InitiativeUser();
                                iu.InitiativeID = initative.ID;
                                iu.UserID = al.UserID;
                                iu.State = "Participated";
                                db.InitiativeUsers.Add(iu);
                                db.SaveChanges();
                            }
                            else
                            {
                                //TODO: Stworzyć poprawną wiadomość z danymi konkretnej inicjatywy :)
                                Email.SendEmail(al.User.Email, "[Portal inicjatyw]", "Niestety nie ma już miejsc na wybraną inicjatywę");
                            }
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.Write("Niezaakceptowana ");
                    }
                    System.Diagnostics.Debug.Write("przez użytkownika: " + acceptanceMessage.getAttendeeEmail() + "\n");
                }
            }
        }
// END OF TEMPLATE METHODS





        public void StopWork()
        {
            working = false;

        }

        public bool isStopped()
        {
            return stopped;
        }

    }

     //public void DoWork()
     //   {
     //       System.Diagnostics.Debug.Write("Starting EmailPopWorker Thread\n");
     //       //sleep a bit at the begining
     //       Thread.Sleep(2000);
     //       working = true;
     //       stopped = false;
     //       //connect to the server
     //       try{
     //       using (Pop3Client client = new Pop3Client())
     //       {
     //           //---MAIN LOOP

     //               while (working)
     //               {
     //                   //make sure client is connected
     //                   if (!client.Connected)
     //                   {
     //                       // Connect to the server
     //                       client.Connect("pop.gmail.com", 995, true);

     //                       // Authenticate
     //                       client.Authenticate(SettingsManager.GetSettingValue("Outlook.Email.Address"), SettingsManager.GetSettingValue("Outlook.Email.Password"));
     //                   }
     //                   // Get the number of messages in the inbox
     //                   int messageCount = client.GetMessageCount();

     //                   //download all messages
     //                   List<Message> allMessages = new List<Message>(messageCount);

     //                   for (int i = messageCount; i > 0; i--)
     //                   {
     //                       allMessages.Add(client.GetMessage(i));
     //                   }
     //                   List<String> rawTextMessages = new List<String>(messageCount);
     //                   foreach (Message item in allMessages)
     //                   {
     //                       String textVersion;
     //                       List<MessagePart> textVersions = item.FindAllTextVersions();
     //                       if (textVersions.Count >= 1)
     //                           textVersion = textVersions[0].GetBodyAsText();
     //                       else
     //                           textVersion = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";

     //                       rawTextMessages.Add(textVersion);
     //                       System.Diagnostics.Debug.Write("Sciagnieto wiaadomosci: " + messageCount + "\n");
     //                   }
     //                   int counter = 0;
     //                   //print out the messages
     //                   foreach (String s in rawTextMessages)
     //                   {
     //                       counter++;
     //                       System.Diagnostics.Debug.Write("---WIADOMOŚĆ: " + counter + " ---\n");
     //                       System.Diagnostics.Debug.Write(s + "\n\n\n");
     //                   }

     //                   //parse messages
     //                   OutlookMeetingParser outlookMeetingParser = new OutlookMeetingParser();
     //                   List<AcceptanceMessage> acceptanceMessages = new List<AcceptanceMessage>();

     //                   if (rawTextMessages != null)
     //                   {
     //                       //this list now have all the info about users acceptances
     //                       acceptanceMessages = outlookMeetingParser.parseMessages(rawTextMessages);
     //                       foreach (AcceptanceMessage acceptanceMessage in acceptanceMessages)
     //                       {
     //                           System.Diagnostics.Debug.Write("Iniciatywa ID: " + acceptanceMessage.getUID() + " ");

     //                           if (acceptanceMessage.isAccepted())
     //                           {
     //                               System.Diagnostics.Debug.Write("Zaakceptowana ");
     //                           }
     //                           else
     //                           {
     //                               System.Diagnostics.Debug.Write("Niezaakceptowana ");
     //                           }
     //                           System.Diagnostics.Debug.Write("przez użytkownika: " + acceptanceMessage.getAttendeeEmail() + "\n");
     //                       }
     //                   }
     //                   else
     //                   {
     //                       //no messages in this iteration
     //                   }
     //                   Thread.Sleep(2000);//sleep a bit every iteration
     //                   client.Disconnect();
     //               }
     //               //------END LOOP
     //           }
     //       }
     //       catch (Exception ex)
     //       {
     //           stopped = true;
     //           System.Diagnostics.Debug.Write("EmailPopWorker.DoWork() exception: " + ex.Message + "\n");
     //           Notify();
     //       }
     //       stopped = true;
     //   }
}